<script lang="ts" setup>
import type { UpdateRiskControlAttachmentRequest } from '@/types/api/order'
import type { Ref } from 'vue'
import { orderApi } from '@/request/api'
import { useConsole, useHideLoading, useLoading, useModal, useNav, useNavBack, useRouteGuard } from '@/utils'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { to } from 'await-to-js'
import { isEmpty, isNil } from 'lodash-es'
import { reactive, ref } from 'vue'
import { any as zany, array as zarray, object as zobject, record as zrecord, string as zstring } from 'zod'

const oid = ref() as Ref<number>
const mode = ref() as Ref<number> // 0 手机  1 电动车

const form = reactive<Record<string, any>>({
  workCertificate: [],
  incomeCertificate: [],
  zhimaCreditRecording: [],
  assetCertificate: [],
  otherDocuments: [],
  contactPerson: {
    userNameOne: '',
    userPhoneOne: '',
    userUrlOne: [],
    emergencyContactOne: '',
    userNameTwo: '',
    userPhoneTwo: '',
    userUrlTwo: [],
    emergencyContactTwo: '',
  },
})
const emergencyContactOptions1 = ['父亲', '母亲', '兄弟姐妹']
const emergencyContactOnePickerIndex = ref<number>()
const emergencyContactOptions2 = ['父亲', '母亲', '兄弟姐妹', '配偶', '其他亲属', '朋友', '同事']
const emergencyContactTwoPickerIndex = ref<number>()

onLoad(async (query) => {
  const zparse = zobject({
    oid: zstring().regex(/^\d+$/).transform(Number),
    mode: zstring().regex(/^\d+$/).transform(Number),
  }).safeParse(query)
  if (!zparse.success) {
    return await useRouteGuard()
  }

  oid.value = zparse.data.oid
  mode.value = zparse.data.mode

  getInfo()
})

onUnload(() => {
  uni.$emit('refreshOrderDetail')
})

async function getInfo() {
  useLoading(true)
  const [err, res] = await to(
    orderApi.getRiskControlAttachment(oid.value),
  )
  useHideLoading()
  if (err) {
    return
  }

  form.workCertificate = res.workCertificate ?? []
  form.incomeCertificate = res.incomeCertificate ?? []
  form.zhimaCreditRecording = res.zhimaCreditRecording ?? []
  form.assetCertificate = res.assetCertificate ?? []
  form.otherDocuments = res.otherDocuments ?? []
  form.contactPerson = {
    userNameOne: res.contactPerson?.userNameOne ?? '',
    userPhoneOne: res.contactPerson?.userPhoneOne ?? '',
    userUrlOne: res.contactPerson?.userUrlOne ?? [],
    emergencyContactOne: res.contactPerson?.emergencyContactOne ?? '',
    userNameTwo: res.contactPerson?.userNameTwo ?? '',
    userPhoneTwo: res.contactPerson?.userPhoneTwo ?? '',
    userUrlTwo: res.contactPerson?.userUrlTwo ?? [],
    emergencyContactTwo: res.contactPerson?.emergencyContactTwo ?? '',
  }
}

function handleChangeEmergencyContactOne(e: any) {
  emergencyContactOnePickerIndex.value = e.detail.value
  form.contactPerson.emergencyContactOne = emergencyContactOptions1[e.detail.value]
}
function handleChangeEmergencyContactTwo(e: any) {
  emergencyContactTwoPickerIndex.value = e.detail.value
  form.contactPerson.emergencyContactTwo = emergencyContactOptions2[e.detail.value]
}

async function handleSubmit() {
  const nameRegex = /^[\u4E00-\u9FA5]{2,20}$/
  const phoneRegex = /^1[3-9]\d{9}$/

  const scheme = zobject({
    workCertificate: zarray(zrecord(zany())).min(1, { message: '工作证明必填' }),
    incomeCertificate: zarray(zrecord(zany())).min(1, { message: '收入证明必填' }),
    contactPerson: zobject({
      userNameOne: zstring().trim().regex(nameRegex, { message: '请填写2-20位中文联系人1姓名' }),
      userPhoneOne: zstring().trim().regex(phoneRegex, { message: '请填写正确格式联系人1电话' }),
      emergencyContactOne: zstring().min(1, { message: '请选择联系人1的亲属关系' }),
      userUrlOne: (() => [
        zarray(zrecord(zany())).min(1, { message: '请上传联系人1的证明图片或视频' }),
        zarray(zrecord(zany())),
      ][mode.value])(),
      userNameTwo: zstring().trim().regex(nameRegex, { message: '请填写2-20位中文联系人2姓名' }),
      userPhoneTwo: zstring().trim().regex(phoneRegex, { message: '请填写正确格式联系人2电话' }),
      emergencyContactTwo: zstring().min(1, { message: '请选择联系人2的亲属关系' }),
      // userNameTwo: (() => [
      //   zstring().trim().regex(nameRegex, { message: '请填写2-20位中文联系人2姓名' }),
      //   zstring().trim().refine(x => isEmpty(x) || nameRegex.test(x), { message: '请填写2-20位中文联系人1姓名' }),
      // ][mode.value])(),
      // userPhoneTwo: (() => [
      //   zstring().trim().regex(phoneRegex, { message: '请填写正确格式联系人2电话' }),
      //   zstring().trim().refine(x => isEmpty(x) || phoneRegex.test(x), { message: '请填写正确格式联系人2电话' }),
      // ][mode.value])(),
      // emergencyContactTwo: (() => [
      //   zstring().min(1, { message: '请选择联系人2的亲属关系' }),
      //   zstring(),
      // ][mode.value])(),
      userUrlTwo: (() => [
        zarray(zrecord(zany())).min(1, { message: '请上传联系人2的证明图片或视频' }),
        zarray(zrecord(zany())),
      ][mode.value])(),
    }),
    zhimaCreditRecording: zarray(zrecord(zany())).min(1, { message: '芝麻信用录屏文件必填' }),
    assetCertificate: zarray(zrecord(zany())),
    otherDocuments: zarray(zrecord(zany())),
  })
  const zparse = scheme.safeParse(form)
  if (!zparse.success) {
    await useModal({
      title: '提示',
      content: zparse.error.issues[0].message,
      showCancel: false,
      confirmText: '好的',
    })
    return
  }

  useConsole?.log(zparse.data)

  useLoading(true)
  const [err] = await to(
    orderApi.updateRiskControlAttachment(oid.value, zparse.data as UpdateRiskControlAttachmentRequest),
  )
  useHideLoading()
  if (err) {
    return
  }

  await useModal({
    title: '提示',
    content: '提交成功',
    showCancel: false,
    confirmText: '返回',
  })

  useNavBack()
  // useRelaunch('/order/index')

  // useRelaunch('/attachment/result', {
  //   status: 'success',
  //   title: '操作成功',
  //   subtitle: '请返回上一页',
  // })

  // my.alert({
  //   title: '提示',
  //   content: '提交成功',
  //   buttonText: '返回上一页',
  //   success: () => {
  //     my.navigateBack()
  //   },
  // })
}

function handleNavHelp(key: string) {
  useNav('/attachment/help', { anchor: `risk-control_${key}` })
}
</script>

<template>
  <view class="px-30px pt-20px">

    <view class="rd-16px bg-white px-20px pb-20px">
      <view class="h-80px flex items-center pl-10px">
        <view class="text-28px text-#3">工作证明</view>
        <view class="ml-10px text-24px text-[red]">(必填)</view>

        <view class="text-theme-primary ml-a text-28px lh-50px" @click="handleNavHelp('workCertificate')">查看指引</view>
      </view>
      <cm-media-list-slim :file-list="form.workCertificate"></cm-media-list-slim>
    </view>

    <view class="mt-10px rd-16px bg-white px-20px pb-20px">
      <view class="h-80px flex items-center pl-10px">
        <view class="text-28px text-#3">收入证明</view>
        <view class="ml-10px text-24px text-[red]">(必填)</view>

        <view class="text-theme-primary ml-a text-28px lh-50px" @click="handleNavHelp('incomeCertificate')">查看指引</view>
      </view>
      <cm-media-list-slim :file-list="form.incomeCertificate"></cm-media-list-slim>
    </view>

    <view class="mt-10px rd-16px bg-white px-20px pb-20px">
      <view class="h-80px flex items-center pl-10px">
        <view class="text-28px text-#3">联系人 1</view>
        <view class="ml-10px text-24px text-[red]">(必填)</view>

        <view class="text-theme-primary ml-a text-28px lh-50px" @click="handleNavHelp('userOne')">查看指引</view>
      </view>

      <view class="flex items-center px-10px">
        <view class="text-24px text-#3 lh-90px">姓名</view>
        <input v-model="form.contactPerson.userNameOne" class="h-90px flex-1 text-right text-24px lh-90px" maxlength="11" placeholder="请填写姓名">
      </view>
      <view class="flex items-center b-t-1px b-t-#e0 b-t-solid px-10px">
        <view class="text-24px text-#3 lh-90px">电话</view>
        <input v-model="form.contactPerson.userPhoneOne" class="h-90px flex-1 text-right text-24px lh-90px" maxlength="11" placeholder="请填写联系人电话">
      </view>
      <view class="flex items-center b-t-1px b-t-#e0 b-t-solid px-10px">
        <view class="text-24px text-#3 lh-90px">亲属关系</view>
        <view class="h-90px flex-1">
          <picker :value="emergencyContactOnePickerIndex" class="h-full w-full" :range="emergencyContactOptions1" @change="handleChangeEmergencyContactOne">
            <view class="h-90px flex items-center justify-end text-24px">
              <view v-if="isNil(emergencyContactOnePickerIndex)" class="text-#80">请选择亲属关系</view>
              <view v-else class="">{{ emergencyContactOptions1[emergencyContactOnePickerIndex] }}</view>
            </view>
          </picker>
        </view>
      </view>
      <view v-if="mode === 0" class="flex items-center b-t-1px b-t-#e0 b-t-solid px-10px">
        <view class="flex text-24px text-#3">
          <view class="lh-90px">图片/视频</view>
          <!-- <view class="ml-10px text-gray-400 lh-90px">添加多张联系人证件或有效性图片</view> -->
        </view>
      </view>
      <cm-media-list-slim v-if="mode === 0" :file-list="form.contactPerson.userUrlOne"></cm-media-list-slim>
    </view>

    <view class="mt-10px rd-16px bg-white px-20px pb-20px">
      <view class="h-80px flex items-center pl-10px">
        <view class="text-28px text-#3">联系人 2</view>
        <view class="ml-10px text-24px text-[red]">(必填)</view>

        <view class="text-theme-primary ml-a text-28px lh-50px" @click="handleNavHelp('userTwo')">查看指引</view>
      </view>

      <view class="flex items-center px-10px">
        <view class="text-24px text-#3 lh-90px">姓名</view>
        <input v-model="form.contactPerson.userNameTwo" class="h-90px flex-1 text-right text-24px lh-90px" maxlength="11" placeholder="请填写姓名">
      </view>
      <view class="flex items-center b-t-1px b-t-#e0 b-t-solid px-10px">
        <view class="text-24px text-#3 lh-90px">电话</view>
        <input v-model="form.contactPerson.userPhoneTwo" class="h-90px flex-1 text-right text-24px lh-90px" maxlength="11" placeholder="请填写联系人电话">
      </view>
      <view class="flex items-center b-t-1px b-t-#e0 b-t-solid px-10px">
        <view class="text-24px text-#3 lh-90px">亲属关系</view>
        <view class="h-90px flex-1">
          <picker :value="emergencyContactTwoPickerIndex" class="h-full w-full" :range="emergencyContactOptions2" @change="handleChangeEmergencyContactTwo">
            <view class="h-90px flex items-center justify-end text-24px">
              <view v-if="isNil(emergencyContactTwoPickerIndex)" class="text-#80">请选择亲属关系</view>
              <view v-else class="">{{ emergencyContactOptions2[emergencyContactTwoPickerIndex] }}</view>
            </view>
          </picker>
        </view>
      </view>
      <view class="flex items-center b-t-1px b-t-#e0 b-t-solid px-10px">
        <view class="flex text-24px text-#3">
          <view class="lh-90px">通讯录{{ mode === 0 ? '' : '(需补录时上传)' }}</view>
          <!-- <view class="ml-10px text-gray-400 lh-90px">添加多张联系人证件或有效性图片</view> -->
        </view>
      </view>
      <cm-media-list-slim :file-list="form.contactPerson.userUrlTwo"></cm-media-list-slim>
    </view>

    <view class="mt-10px rd-16px bg-white px-20px pb-20px">
      <view class="h-80px flex items-center pl-10px">
        <view class="text-28px text-#3">芝麻信用录屏文件</view>
        <view class="ml-10px text-24px text-[red]">(必填)</view>

        <view class="text-theme-primary ml-a text-28px lh-50px" @click="handleNavHelp('zhimaCreditRecording')">查看指引</view>
      </view>
      <cm-media-list-slim :file-list="form.zhimaCreditRecording"></cm-media-list-slim>
    </view>

    <view class="mt-10px rd-16px bg-white px-20px pb-20px">
      <view class="h-80px flex items-center pl-10px">
        <view class="text-28px text-#3">资产证明</view>

        <view class="text-theme-primary ml-a text-28px lh-50px" @click="handleNavHelp('assetCertificate')">查看指引</view>
      </view>
      <cm-media-list-slim :file-list="form.assetCertificate"></cm-media-list-slim>
    </view>

    <view class="mt-10px rd-16px bg-white px-20px pb-20px">
      <view class="h-80px flex items-center pl-10px">
        <view class="text-28px text-#3">其他材料</view>
      </view>
      <cm-media-list-slim :file-list="form.otherDocuments"></cm-media-list-slim>
    </view>

    <view class="safe-pb-15px">
      <view class="h-115px"></view>
    </view>
  </view>

  <view class="fixed bottom-0 w-full flex bg-white pt-15px safe-pb-15px">
    <view class="btn-primary-black mx-a w-600px text-36px lh-80px" @click="handleSubmit">提交</view>
  </view>
</template>

<style lang="less" scoped></style>
